import { ColorModel } from "@/global/const"

// 改变主题模式
export const handleThemeChange = (val: string) => {
  const colorModel = local.get(ColorModel)
  if (val === 'dark') {
    document.documentElement.setAttribute('theme', 'dark')
  } else {
    document.documentElement.removeAttribute('theme')
  }
  colorModel === val ? '' : local.set(ColorModel, val)
}

// 切换中英模式
export const changeLang = (str: string): Promise<string | null> => {
  return new Promise((res) => {

  })
}

// 跟随系统主题模式
export const followSystemModel = () => {
  const colorModel = local.get(ColorModel)
  if (colorModel) {
    if (local.get(ColorModel) === 'dark') {
      handleThemeChange('dark')
    } else {
      handleThemeChange('light')
    }
  } else {
    const scheme = window.matchMedia('(prefers-color-scheme: dark)')
    if (scheme.matches) {
      handleThemeChange('dark')
    } else {
      handleThemeChange('light')
    }
  }
}

// 封装localStorage
export const local = {
  // 储存
  set(key: string, value: any) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  // 取出数据
  get(key: string) {
    try {
      const value = localStorage.getItem(key);
      if (value === null || value === undefined || value === '') {
        return null
      }
      return JSON.parse(value)
    } catch (err) {
      return null
    }
  },
  // 删除数据
  remove(key: string) {
    localStorage.removeItem(key)
  }
}

// 封装sessionStorage
export const session = {
  //存储
  set(key: string, value: any) {
    sessionStorage.setItem(key, JSON.stringify(value));
  },
  //取出数据
  get(key: string) {
    try {
      const value = sessionStorage.getItem(key);
      if (value === null || value === undefined || value === "") {
        return null;
      }
      return JSON.parse(value);
    } catch (err) {
      return null
    }
  },
  // 删除数据
  remove(key: string) {
    sessionStorage.removeItem(key);
  }
}

// 标题改变
export const updateTitle = (title: string) => {
  if (typeof document.title === 'string' || (document.title === undefined || document.title === null)) {
    document.title = title
    return true
  } else {
    return new Error('修改失败')
  }
}

// debounce 加强版
export function useDebounce<A extends any[], R = void>(fn: (...args: A) => R, delay: number) {
  let timeOut: null | NodeJS.Timeout = null;
  let args: A;
  function debounced(..._args: A) {
    args = _args
    if (timeOut) {
      clearTimeout(timeOut)
      timeOut = null
    }
    return new Promise((res, rej) => {
      timeOut = setTimeout(() => {
        try {
          const result = fn.apply(null, _args);
          res(result)
        } catch (err) {
          rej(err)
        }
      }, delay)
    })
  }
  function cancel() {
    if (!timeOut) return
    clearTimeout(timeOut)
    timeOut = null
  }
  function flush() {
    cancel()
    return fn.apply(null, args)
  }
  debounced.flush = flush
  debounced.cancel = cancel
  return debounced
}

